package ch.uzh.ifi.seal.ssqa.ui.decorator;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.internal.resources.Resource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;

import ch.uzh.ifi.seal.ssqa.model.DiagramComponent;
import ch.uzh.ifi.seal.ssqa.model.diagram.part.SsqaDiagramEditor;
import ch.uzh.ifi.seal.ssqa.util.DiagramComponentProvider;

@SuppressWarnings("restriction")
public class SourceMappingDecorator extends LabelProvider implements
		ILabelDecorator {
	@Override
	public Image decorateImage(Image image, Object element) {
		image.setBackground(new Color(null, new RGB(255, 0, 0)));
		return null;
	}

	@Override
	public String decorateText(String text, Object element) {
		try {
			IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
			IEditorPart part = page.getActiveEditor();
			if(part instanceof SsqaDiagramEditor){
				SsqaDiagramEditor editor = ((SsqaDiagramEditor)part);
				FileEditorInput input = (FileEditorInput) ((IEditorPart) editor).getEditorInput();
				DiagramComponentProvider provider = new DiagramComponentProvider(input.getFile());
				List<String> sourceFiles = new ArrayList<String>();
				for(DiagramComponent component : provider.getDiagramComponents()){
					sourceFiles.addAll(component.getSourcePaths());
				}
				if(element instanceof Resource){
					IPath path = ((Resource)element).getFullPath();
					if(this.checkParentMapping(path, sourceFiles)){
						return text + " (mapped)";
					}
				}
			}
			return null;
		} catch (Exception e){
			return null;
		}
	}
	
	private boolean checkParentMapping(IPath path, List<String> files){
		boolean check = false;
		String pathString = path.toString();
		while(pathString.contains("/")){
			System.out.println(pathString);
			if(files.contains(pathString)){
				check = true;
			}
			pathString = pathString.substring(0, pathString.lastIndexOf("/"));
		}
		return check;
	}
}
